<template>
  <div class="top-banner-wrapper">
    <div class="banner-images-box">
      <swiper class="banner-swiper" circular @change="swiperChange" swiperDuration="250">
        <swiper-item v-for="(item, index) in displaySwiperList" :key="index" @click="previewImage(item.url)">
          <image mode="aspectFill" class="slide-image" :src="`${item.url}?x-oss-process=image/resize,m_fixed,h_750`" />
        </swiper-item>
      </swiper>
      <scroll-view scroll-x scroll-with-animation :enhanced="true" :show-scrollbar="false" class="scroll-view" :scroll-into-view="intoViewId">
        <div class="scroll-wrapper">
          <div
            class="indicator-dots"
            v-for="item in indicatorTitles"
            :key="item.type"
            @click="switchTitle(item.type)"
            :id="item.type"
            :class="{ active: currentImage.type == item.type }"
          >
            <span class="name">{{ item.name }}</span>
          </div>
        </div>
      </scroll-view>
      <div class="pages-number" v-if="thumbCount > 0" v-show="!['video', 'vr'].includes(currentImage.type)">{{ currentNumber }} / {{ thumbCount }}</div>
      <div class="vr-play-button" @click="openVR()" v-show="['vr'].includes(currentImage.type) && vrCover">
        <image :src="$CDN('/customer/static/images/icons/vr-big.png')" />
      </div>
      <div class="vr-play-button" @click="playVideo()" v-show="['video'].includes(currentImage.type) && videoCover && !fullScreenPlay">
        <image :src="$CDN('/customer/static/images/icons/video-big.png')" />
      </div>
      <div class="full-screen">
        <video
          id="myVideo"
          class="banner-video"
          :src="videoUrl"
          @timeupdate="handleTimeUpdate"
          @fullscreenchange="fullScreenChange"
          @ended="handleVideoEnded"
          @error="error"
        ></video>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'componentName',
  components: {},
  mixins: [],
  props: {
    vrCover: {
      type: String,
      default: '',
    },
    videoCover: {
      type: String,
      default: '',
    },
    videoUrl: {
      type: String,
      default: '',
    },
    projectImages: {
      type: Array,
      default: () => [],
      required: true,
    },
    fromSource: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      originSwiperList: [], // 原始数据
      indicatorTitles: [], // 模拟中间的点击点
      displayMultipleItems: 0, // 滑块数
      displaySwiperList: [], // 显示的swiper数据
      displayIndex: 0, // 当前显示的索引
      originIndex: 0, // 本来的索引
      currentImage: {},
      intoViewId: '',
      preview: false,
      previewImageList: [],
      videoContext: null,
      fullScreenPlay: false,
      isVideoEnded: false,
      playState: false,
      updateTime: 0,
      currentNumber: 0,
      thumbCount: 0, // 相册总数
    }
  },
  // 侦听属性
  watch: {},
  // 计算属性
  computed: {
    ...mapGetters([]),
  },
  // 监听页面加载，该钩子被调用时data,computed,function,watch,props,slots已设置完成
  onLoad(options) {},
  // 监听页面显示，页面每次出现在屏幕上都触发
  onShow() {},
  // 监听页面初次渲染完成，此时组件已挂载完成
  onReady() {},
  // 下拉刷新
  onPullDownRefresh() {},
  // 加载更多
  onReachBottom() {},

  created() {},
  mounted() {
    this.generatingObject()
    this.initVideo()
  },
  destroyed() {},
  methods: {
    initVideo() {
      this.$nextTick(() => {
        this.videoContext = uni.createVideoContext('myVideo', this)
      })
      // this.videoContext = uni.createVideoContext('myVideo', this)
    },
    // 将后台数据图片数据初始化成一个
    generatingObject() {
      const projectImages = this.projectImages
      let imageList = []
      let titles = []
      let previewImages = []
      if (projectImages.length <= 0) return
      // 展开 images 对象数组
      projectImages.flatMap((group, index) => {
        const type = `thumb-${index + 1}`
        const imageItems = group.data.map((img, idx) => ({
          id: `thumb-${index + 1}-${idx}`,
          type,
          url: img,
          name: group.name,
        }))
        const titleItems = { name: group.name, type }
        imageList = [...imageList, ...imageItems]
        titles = [...titles, titleItems]
        previewImages = [...previewImages, ...group.data]
      })
      const vrItem = { name: 'VR', id: 'vr-0', type: 'vr' }
      const videoItems = { name: '视频', type: 'video', id: 'video-0' }
      // 插入vr 和 video 前计算图片总张数
      this.thumbCount = imageList.length
      // 图片汇集
      this.previewImageList = previewImages
      if (this.videoCover) {
        titles = [videoItems, ...titles]
        imageList = [{ ...videoItems, url: this.videoCover }, ...imageList]
      }
      if (this.vrCover) {
        titles = [vrItem, ...titles]
        imageList = [{ ...vrItem, url: this.vrCover }, ...imageList]
      }
      this.originSwiperList = imageList
      this.indicatorTitles = titles
      this.initSwiperData()
      // console.log('image list:', imageList)
      // console.log('titles data>>>>', titles)
    },
    // 处理幻灯片数据每次只显示3条
    initSwiperData(originIndex = this.originIndex) {
      const originListLength = this.originSwiperList.length // 源数据长度
      const displayList = []
      displayList[this.displayIndex] = this.originSwiperList[originIndex]
      displayList[this.displayIndex - 1 == -1 ? 2 : this.displayIndex - 1] = this.originSwiperList[originIndex - 1 == -1 ? originListLength - 1 : originIndex - 1]
      displayList[this.displayIndex + 1 == 3 ? 0 : this.displayIndex + 1] = this.originSwiperList[originIndex + 1 == originListLength ? 0 : originIndex + 1]
      this.displaySwiperList = displayList
      this.currentImage = this.originSwiperList[originIndex]
      this.currentNumber = this.vrCover && this.videoCover ? originIndex - 1 : this.vrCover || this.videoCover ? originIndex : originIndex + 1
      // console.log('swiper image info:', this.currentImage)
      this.intoViewId = this.currentImage.type
      // 数据埋点
      this.$emit('changeSwiper', this.currentImage.name)
    },
    // 幻灯片滑动
    swiperChange(event) {
      const { current } = event.detail
      const originListLength = this.originSwiperList.length // 源数据长度
      // =============向后==========
      if (this.displayIndex - current == 2 || this.displayIndex - current == -1) {
        this.originIndex = this.originIndex + 1 == originListLength ? 0 : this.originIndex + 1
        this.displayIndex = this.displayIndex + 1 == 3 ? 0 : this.displayIndex + 1
        this.initSwiperData(this.originIndex)
        return
      }
      // ======如果两者的差为-2或者1则是向前滑动============
      if (this.displayIndex - current == -2 || this.displayIndex - current == 1) {
        this.originIndex = this.originIndex - 1 == -1 ? originListLength - 1 : this.originIndex - 1
        this.displayIndex = this.displayIndex - 1 == -1 ? 2 : this.displayIndex - 1
        this.initSwiperData(this.originIndex)
      }
    },
    // 点击底部title切换幻灯片
    switchTitle(type) {
      const originIndex = this.originSwiperList.findIndex((item) => item.type === type)
      this.originIndex = originIndex
      this.initSwiperData(originIndex)
    },
    openVR() {
      this.preview = true
      this.$emit('openVR')
    },
    playVideo() {
      this.videoContext.play()
      this.videoContext.requestFullScreen({ direction: 0 })
      this.fullScreenPlay = false
      this.playState = true
    },
    previewImage(url) {
      // 如果是 视频和vr 点击则不预览图片
      if (['video', 'vr'].includes(this.currentImage.type)) return
      uni.previewImage({
        urls: this.previewImageList, // 需要预览的图片http链接列表
        current: url,
        showmenu: false,
      })
    },
    fullScreenChange(e) {
      if (e && e.detail) {
        const fullScreen = e.detail.fullScreen
        if (!fullScreen) {
          // #ifdef APP-PLUS
          plus.screen.lockOrientation('portrait-primary')
          // #endif
          this.videoContext.stop()
          this.fullScreenPlay = false
          this.playState = false
        }
      }
    },
    handleVideoEnded(e) {
      this.isVideoEnded = true
      this.$emit('videoEnded')
    },
    handleTimeUpdate(e) {
      if (e.type == 'onFullscreenchange') {
        this.videoContext.stop()
      }
      this.updateTime = e.detail.currentTime
      if (this.playState) {
        this.$emit('videoEnded')
      }
    },
    submitVideoTime() {
      let obj = {
        time: this.updateTime,
        isEnded: this.isVideoEnded,
      }
      return obj
    },
    error(e) {
      uni.$uv.toast('视频不见了~')
      // #ifdef APP-PLUS
      plus.screen.lockOrientation('portrait-primary')
      // #endif
      this.fullScreenPlay = false
      this.playState = false
    },
  },
}
</script>

<style lang="scss" scoped>
.top-banner-wrapper,
.banner-images-box,
.banner-swiper {
  height: 100%;
  width: 100%;
}
.slide-image {
  display: block;
  width: 100%;
  height: 100%;
}
.banner-images-box {
  position: relative;
}

.scroll-view {
  position: absolute;
  left: 50%;
  bottom: 24rpx;
  transform: translateX(-50%);
  width: auto;
  max-width: 464rpx;
  height: 48rpx;
  line-height: 40rpx;
  z-index: 100;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 200rpx;
  overflow: hidden;
  box-sizing: border-box;
}
.scroll-wrapper {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
}
.scroll-view .indicator-dots {
  font-size: 24rpx;
  font-weight: 400;
  color: #222222;
  white-space: nowrap;
  height: 48rpx;
  line-height: 48rpx;
  line-height: 34rpx;
  padding: 8rpx 16rpx;
  box-sizing: border-box;
  width: fit-content;
}
.scroll-view .indicator-dots.active {
  background: $uv-primary;
  font-weight: bold;
  color: #ffffff;
  border-radius: 200rpx;
}

.pages-number {
  position: absolute;
  right: 16rpx;
  bottom: 24rpx;
  // width: 84rpx;
  height: 48rpx;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 24rpx;
  box-sizing: border-box;
  padding: 6rpx 16rpx 8rpx 16rpx;
  color: #ffffff;
  line-height: 34rpx;
  font-size: 24rpx;
}
.vr-play-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  image {
    width: 104rpx;
    height: 104rpx;
  }
}

.banner-video {
  // width: 100%;
  // height: 100%;
  width: 1px;
  height: 1px;
  // height: calc(100% - constant(safe-area-inset-bottom));
  // height: calc(100% - env(safe-area-inset-bottom));
}
.top-banner-wrapper {
  position: relative;
}
</style>
